class Game {
	constructor(id, integral) {
		this.panel = document.querySelector(id);
		this.integralPanel = document.querySelector(integral)
		// this.integral = 0;
		this.size = 20;
		this.timer = null;
	}
	render() {
		// 实例化食物
		this.food = new Food({
			panel: this.panel,
			size: this.size
		})
		// 实例化蛇
		this.snake = new Snake({
			panel: this.panel,
			size: this.size
		})
		// 实例化积分
		this.score = new Score();
		// 
		this.food.render()
		this.snake.render()
	}
	run() {
		
		// 设置历史分数
		this.setHiscopeRender()
		// 控制方向
		this.dirControl()
		// 移动，渲染
		this.timer = setInterval(() => {
			// 设置等级
			this.setLevelRender()
			this.snake.move(this.food)
			this.snake.render()
			this.borderControl()
			this.collision(this.food.getPoint(), this.snake.getPoint())
		}, 200)

	}
	// 停止运行
	stop() {
		clearInterval(this.timer);
	}
	// 重新运行
	reset() {
		// 设置历史分数
		this.setHiscopeRender()
		// 蛇重新初始化
		this.snake.init()
		this.render()
		this.run()
	}
	// 清空画布元素
	clear() {
		// 清空积分
		this.score.clear()
		// 渲染到do'm
		this.setIntegralRender() 
		this.snake.remove()
		this.food.remove()
	}
	// 边界判断
	borderControl() {
		let maxX = (this.panel.clientWidth / this.size);
		let maxY = (this.panel.clientHeight / this.size);
		let snakeHead = this.snake.getPoint();
		if (snakeHead.x < 0 || snakeHead.x >= maxX || snakeHead.y < 0 || snakeHead.y >= maxY) {
			this.stop()
			if (confirm('~~输了，需要继续吗')) {
				this.score.history=this.score.getVal()
				this.clear()
				this.reset()
			} else {
				this.score.history=this.score.getVal()
			}

		}
	}
	// 方向控制
	dirControl() {
		document.addEventListener('keydown', (e) => {
			let dir = this.snake.direction;
			switch (e.keyCode) {
				case 68:
				case 39:
					if(dir!=='left'){
						this.snake.direction = 'right';
					}
					break;
				case 83:
				case 40:
					if(dir!=='top'){
						this.snake.direction = 'bottom';
					}
					break;
				case 65:
				case 37:
					if(dir!=='right'){
						this.snake.direction = 'left';
					}
					break;
				case 87:
				case 38:
					if(dir!=='bottom'){
						this.snake.direction = 'top';
					}
					break;
				default:
					break;
			}
		})
	}
	// 碰撞检测
	collision(food, snake) {
		if (snake.x === food.x && snake.y === food.y) {
			// 蛇增加一节
			this.snake.add()
			// 食物重新渲染
			this.food.render()
			// 积分+1
			this.score.setVal();
			this.setIntegralRender()
		}
	}
	// 渲染到分数do'm
	setIntegralRender(){
		this.integralPanel.innerHTML = this.score.getFormat(this.score.getVal());
	}
	// 渲染历史分数dom
	setHiscopeRender(){
		document.querySelector('#history').innerHTML= this.score.getFormat(this.score.history);
	}
	setLevelRender(){
		console.log( this.score.level);
		document.querySelector('#Level').innerHTML= this.score.level;
	}

}
